package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.analyse.JSoupUtils;
import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.RegexUtils;
import com.kdtech.utils.StringUtils;
import com.kdtech.utils.HtmlCleaner;

/**
 *	未完成
 * http://www.btv.org/btvindex/xw/content/2013-05/05/content_7024175.htm  BTV在线
 *
 * @author KK
 *
 */

//网站不存在

public class BtvNewsAnalyse implements AnalyseNews {

	private static final String[] regex={

		"http://.*.brtn.cn/.*/VIDE[0-9]+.shtml",
		"http://.*.brtn.cn/.*/ARTI[0-9]+.shtml",
		"http://tv.brtn.cn/[0-9]{8}/[A-Z0-9]*.shtml",
	};

	
	public boolean isDetailPage(String url) {
		return RegexUtils.matchAnyIgnoreCase(url, regex);
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		if (urlMeta.getHtml() == null) {
		}
		NewsMeta news=new NewsMeta();
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();
		String title=null;
		String content=null;
		String author=null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);
		news.setUrl(url);

		title =doc.select("h1.tit_fls2").text();
		if (StringUtils.isBlank(title)){
			title =doc.select("title").text();
			if (title.contains("-")) title=StringUtils.substringBefore(title, "-");
		}
		content=HtmlCleaner.getContentHtml(url ,doc.select("div.cont p"));
		if (StringUtils.isBlank(content)){
			content=HtmlCleaner.getContentHtml(url ,doc.select(".txt p"));
		}
		if (StringUtils.isBlank(content)){
			content=HtmlCleaner.getContentHtml(url ,doc.select(".text p"));
		}

		author=JSoupUtils.matchAuthor(doc, "来源:");
		if (date==null)date=JSoupUtils.matchDate(doc, "上传时间");
		if (date==null)date=DateUtils.matchDate(doc.select(".from_time").text());
		if (date==null)date=DateUtils.matchDate(doc.select(".date").text());
		if (date==null)date=DateUtils.matchDate(url);
		news.setTitle(StringUtils.trimSpace(title));
		news.setContent(content);
		news.setAuthor(author);
		news.setDate(date);
		news.setType(1);
		return news;
	}
	public static void main(String[] args) {
		String url="http://tv.brtn.cn/20150701/VIDE1435754917253727.shtml";
		BtvNewsAnalyse analyse=new BtvNewsAnalyse();
		System.out.println(analyse.isDetailPage(url));
		UrlMeta meta=CrawlHTML.responseToURL(url);
		System.out.println(analyse.parserHtml(meta));
	}

	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	
	public boolean isNeedUpdate(){
		return false;
	}
}
